<?php

namespace App\Repositories\Manage;

use App\Models\ComboSpec;
use App\Models\ComboSpecItem;
use App\Models\Product;
use App\Models\Supplier;

class ProductRepository
{
    /**
     * product_type  1: 套餐 0：普通
     * spec_type 10:单规格  20： 多规格
     */
    public function getList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $res = (new Product())->setTable("p")->from("product as p")
            ->leftJoin("product_category as c", "c.id", "=", "p.category_id")
            ->when(!empty($filter['keywords']), function ($query) use ($filter) {
                return $query->where("p.title", "like", "%{$filter['keywords']}%");
            })
            ->when(!empty($filter['shop_id']), function ($query) use ($filter) {
                return $query->where("p.shop_id", "=", intval($filter['shop_id']));
            })
            ->when(!empty($filter['category_id']), function ($query) use ($filter) {
                return $query->where("p.category_id", "=", intval($filter['category_id']));
            })
            ->where(['product_type' => intval($filter['product_type'] ?? 0)])
            ->orderBy("p.id", "desc")
            ->paginate($pageSize, ["p.*", "c.title as category_title"], null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);
        foreach ($res['items'] as $k => &$v) {
            $v['shop_title'] = Supplier::query()->where(['id' => $v['shop_id']])->value("title");

//            获取商品规格
            if ($v['product_type'] == 1)
                $v['products'] = (new ComboSpecRepository())->getSpecs($v['id']);

        }

        return $res;
    }

    /**
     * 批量删除
     * @param null $ids
     */
    public function batchDelete($ids = null)
    {
        if (intval($ids)) {
            Product::query()->where(['id' => $ids])->delete();
        } else {
            Product::query()->whereIn("id", $ids)->delete();
        }

        return retSuc([], "删除成功");
    }

    public function saveOrUpdate($data = [], $id = 0)
    {
        if (intval($id)) {
            Product::query()->where("id", $id)->update($data);
            delRedis("productComboSpecList_" . $id, 2);

            if ($data['product_type'] == 1) {
                (new ComboSpecRepository())->getSpecs($id);
            }

            return $id;
        } else {
            // 获取序号
            $sequence = Product::where(['shop_id' => $data['shop_id']])->orderBy("sequence", "desc")->value("sequence");
            $shop_name = Supplier::query()->where(['id' => $data['shop_id']])->value("name");
            if ($sequence > 0) {
                $sequence += 1;
            } else {
                $sequence = 100001;
            }

            $data['sequence'] = $sequence;
            $data['sn'] = $shop_name . '' . $sequence;
            $res = Product::create($data);

            if ($data['product_type'] == 1) {
                (new ComboSpecRepository())->getSpecs($res['id']);
            }

            return $res['id'] ?? "";
        }
    }

    /**
     * 复制商品
     * @param $id
     */
    public function copyProduct(int $id = 0, $uid = 0)
    {
        if (!$id)
            return retFail("数据错误");

        $product = $this->getOne(intval($id));
        if (empty($product))
            return retFail("商品不存在");

        if (!checkIsSuper($uid)) {
            $shop_id = getUserRelateShopId(UID);

            if ($product['shop_id'] != $shop_id) {
                return retFail("您没有权限");
            }
        }
        $product = $product->toArray();
        $skus = $product['skus'] ?? null;
        if (empty($skus)) {
            return retSuc([], "复制成功");
        }

        $product_data = $product;
        $product_data['status'] = 0;
        unset($product_data['id']);
        unset($product_data['create_time']);
        unset($product_data['update_time']);
        unset($product_data['skus']);

        // 获取序号
        $sequence = Product::where(['shop_id' => $product_data['shop_id']])->orderBy("sequence", "desc")->value("sequence");
        $shop_name = Supplier::query()->where(['id' => $product_data['shop_id']])->value("name");
        if ($sequence > 0) {
            $sequence += 1;
        } else {
            $sequence = 100001;
        }
        $product_data['sequence'] = $sequence;
        $product_data['sn'] = $shop_name . '' . $sequence;
        $last_id = Product::create($product_data)->id;
        if (!$last_id)
            return retFail("复制失败");

        if ($product['product_type'] == 1) { //套餐复制

            foreach ($skus as $k => $sku) {
                $sku_data = $sku->toArray();
                unset($sku_data['spec_items']);
                unset($sku_data['id']);
                $sku_data['product_id'] = $last_id;

                $spec_id = ComboSpec::create($sku_data)->id;
                if (!$spec_id)
                    continue;

                $spec_items = $sku['spec_items']->toArray();
                foreach ($spec_items as $k => &$item) {
                    $item['spec_id'] = $spec_id;
//                    $item['product_id'] = $last_id;
                    unset($item['old_id']);
                    unset($item['id']);
                }

                ComboSpecItem::insert($spec_items);
            }
        }

        return retSuc([], "复制成功");
    }

    public function getOne(int $id)
    {
        $res = Product::query()->where(['id' => $id])->first();

        if (isset($res)) {

            $res['seller_time'] = json_decode($res['seller_time']);
            if ($res['product_type'] == 1) {//套餐
                $res['skus'] = (new ComboSpecRepository())->getSpecs($res['id']);
            } else {
                $res['skus'] = (new SpecRepository())->getSpecs($res['id']);
            }
        }


        return $res;
    }

    public function getProducts($word = null, $shop_id = null)
    {
        return (new Product())->setTable("p")
            ->from("product as p")
            ->join("product_category as c", "c.id", "=", "p.category_id")
            ->when(isset($word), function ($query) use ($word) {
                $query->where("p.title", "like", "%{$word}%");
            })
            ->when(isset($shop_id), function ($query) use ($shop_id) {
                $query->where("p.shop_id", intval($shop_id));
            })
            ->get(['p.id', 'p.title', 'c.title as category_title']);
    }

}
